package william.list;

/**
 * @author ZhangShenao
 * @date 2024/1/13
 * @description <a href="https://leetcode.cn/problems/linked-list-cycle/description/">...</a>
 */
public class Leetcode141_环形链表 {
    private class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    /**
     * 使用快、慢指针法：快指针每次前进2个节点,慢指针每次前进1个节点。如果两个指针相遇,则说明链表有环,否则无环
     */
    public boolean hasCycle(ListNode head) {
        //边界条件校验
        if (head == null) {
            return false;
        }

        //声明快、慢两个指针
        ListNode fast = head;
        ListNode slow = head;

        while (fast.next != null && fast.next.next != null && slow.next != null) {
            fast = fast.next.next;  //快指针每次前进2个节点
            slow = slow.next;    //慢指针每次前进1个节点

            //如果两指针相遇,则说明链表有环
            if (fast == slow) {
                return true;
            }
        }

        //循环退出,说明链表遍历结束,则一定无环
        return false;
    }

}
